package com.my.netty.nio.net.block;


import com.my.netty.nio.utils.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class BlockNioServer {

    public static void main(String[] args) throws IOException {
        //NIO的阻塞式TCP服务端（单线程处理，因为线程会阻塞，实际上无法处理）
        ByteBuffer buf = ByteBuffer.allocate(16);

        //1.创建ServerSocketChannel
        ServerSocketChannel ssc = ServerSocketChannel.open();

        //2.监听8080端口
        ssc.bind(new InetSocketAddress(8080));

        List<SocketChannel> socketChannels = new ArrayList<>();
        //3.等待客户端连接
        while (true) {
            log.debug("等待连接...");
            SocketChannel sc = ssc.accept(); //accept默认是阻塞的，有客户端连接时才继续执行
            log.debug("获取连接：{}", sc.getRemoteAddress());
            socketChannels.add(sc);
            //4.接收每个客户端数据
            for (SocketChannel channel : socketChannels) {
                log.debug("等待读取客户端数据... {}", channel.getRemoteAddress());
                channel.read(buf); //read默认也是阻塞的，有客户端发送数据时才继续执行
                //切换为读模式
                buf.flip();
                //5.打印buffer内容
                debugRead(buf);
                //切换为写模式
                buf.clear();
                log.debug("读取客户端数据完成 {}", channel.getRemoteAddress());
            }
        }
    }

    private static void debugRead(ByteBuffer buf) {
        ByteBufferUtil.debugRead(buf);
    }
}
